package com.efounder.chat.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.widget.SwitchCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.db.GetDBHelper;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;


/**
 * @author yqs
 */
@SuppressLint({"SimpleDateFormat", "SdCardPath"})
public class ChatSingleSettingActivity extends BaseActivity implements
        OnClickListener {
    // 、置顶、、、、
    private RelativeLayout re_clear;// 清除聊天记录
    private RelativeLayout rlSwitchChatToTop, rlSwitchBlockGroupmsg;

    // 状态变化
    private SwitchCompat switchTop;// 置顶聊天
    private SwitchCompat switchNotification;// 免打扰

    private int userId;
    private String userNick;
    private String avatar;
    private byte chatType;
    private User user;
    String sex;
    private Boolean isFriend; //判断是否是好友
    //private ImageLoader imageLoader;
//	private DisplayImageOptions options;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_singlechat_setting);
        //initImageLoader();

        userId = getIntent().getIntExtra("id", 1);
        user = WeChatDBManager.getInstance().getOneFriendById(userId);
        isFriend = user.isExist();
        if (!isFriend) {
            user = WeChatDBManager.getInstance().getOneUserById(userId);
        }
        userNick = user.getReMark();
        avatar = user.getAvatar();

        chatType = getIntent().getByteExtra("chattype",
                StructFactory.TO_USER_TYPE_PERSONAL);
        initView();
        initData();

    }

    private void initView() {
        rlSwitchChatToTop = (RelativeLayout) findViewById(R.id.rl_switch_chattotop);
        rlSwitchBlockGroupmsg = (RelativeLayout) findViewById(R.id.rl_switch_block_groupmsg);
        if (!isFriend) {
            rlSwitchChatToTop.setVisibility(View.GONE);
            rlSwitchBlockGroupmsg.setVisibility(View.GONE);
        }
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.chat_chat_message);
        re_clear = (RelativeLayout) findViewById(R.id.re_clear);

        switchTop = (SwitchCompat) findViewById(R.id.switch_top);
        switchNotification = (SwitchCompat) findViewById(R.id.switch_notification);
        switchNotification.setChecked(user.getIsBother());
        switchTop.setChecked(user.getIsTop());
        switchNotification.setOnClickListener(this);
        switchTop.setOnClickListener(this);
    }

    private void initData() {
        re_clear.setOnClickListener(this);

        ImageView iv_avatar = (ImageView) this.findViewById(R.id.iv_avatar);
        TextView tv_username = (TextView) this.findViewById(R.id.tv_username);
        tv_username.setText(userNick);

        LXGlideImageLoader.getInstance().showRoundUserAvatar(ChatSingleSettingActivity.this, iv_avatar, avatar
                , LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
        //点击头像跳转用户信息
        iv_avatar.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.putExtra("id", user.getId());
                intent.putExtra("chattype", chatType);
                ChatActivitySkipUtil.startUserInfoActivity(ChatSingleSettingActivity.this, intent);

            }

        });
        ImageView iv_avatar2 = (ImageView) this.findViewById(R.id.iv_avatar2);
        iv_avatar2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(ChatSingleSettingActivity.this,
                        CreatChatRoomActivity.class).putExtra("selectuser", user));

            }

        });

    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.switch_notification) {
            showLoading(R.string.configuring_friend_info);
            GetHttpUtil.updateFriendInfo(this, user.getId(), "isBother",
                    switchNotification.isChecked() ? "1" : "0", new JFCommonRequestManager.ReqCallBack<String>() {
                        @Override
                        public void onReqSuccess(String result) {
                            dismissLoading();
                            user.setIsBother(switchNotification.isChecked());
                            saveUserInfo(user);
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                            dismissLoading();
                            switchNotification.setChecked(!switchNotification.isChecked());
                            ToastUtils.showShort(R.string.alter_friend_config_fail_retry);
                        }
                    });

        } else if (id == R.id.re_clear) {// 清空消息
            showLoading(ResStringUtil.getString(R.string.chat_clearing_message));

            GetDBHelper.getInstance().getDBHelper().getWritableDatabase().execSQL("update message  set enable = 0 where toUserType = 0 and  (fromUserId =" + userId + " or toUserId =" + userId + ")");

            JFMessageManager.getInstance().getMessageList(userId, StructFactory.TO_USER_TYPE_PERSONAL).clear();
            //TODO 删除列表数据
            ChatListItem chatListItem = new ChatListItem();
            chatListItem.setChatType(StructFactory.TO_USER_TYPE_PERSONAL);
            chatListItem.setUserId(userId);
            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);

            // 按照你们要求必须有个提示，防止记录太少，删得太快，不提示
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                    //WeChatDBManager.getInstance().deleteChatRecord(userId);


                    dismissLoading();
                }

            }, 2000);
        } else if (id == R.id.switch_top) {
            // 消息置顶
            showLoading(R.string.configuring_friend_info);
            GetHttpUtil.updateFriendInfo(this, user.getId(), "isTop",
                    switchTop.isChecked() ? "1" : "0", new JFCommonRequestManager.ReqCallBack<String>() {
                        @Override
                        public void onReqSuccess(String result) {
                            dismissLoading();
                            user.setIsTop(switchTop.isChecked());
                            saveUserInfo(user);
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                            dismissLoading();
                            switchTop.setChecked(!switchTop.isChecked());
                            ToastUtils.showShort(R.string.alter_friend_config_fail_retry);
                        }
                    });
        }

    }

    /**
     * 保存修改后的信息
     *
     * @param user
     */
    private void saveUserInfo(final User user) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    WeChatDBManager.getInstance().insertOrUpdateUser(user);
                }

            }
        }).start();
    }

    @Override
    public void back(View v) {
        this.finish();
    }

    @Override
    protected void onStop() {
        super.onStop();
        notifyChange(user);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void notifyChange(User user) {
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(user.getId(), chatType);
        EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
    }
}
